

# 字典
# key 的 要求：不可变的数据类型，比如字符串、整数、元组，常用：字符串、整数
# 字典的特性1：字典的键是不重复的

# 定义
dic1 = {"name": "张三", "age": 18, "gender": "男"}

dic2 = dict([("name", "李四"), ("age", 19)])      # {"name": "李四", "age": 19}


print(dic1)
# 增加
dic1["hobbies"] = ["唱歌", "跳舞", "打篮球"]
print(dic1)

dic1.update({"study_year": 2.5})
print(dic1)


# 查询
# print(dic1["hobbies"])
# # print(dic1["class"])
#
# print(
#     dic1.get("class", 2302)     # 如果找不到对应的key则返回 默认值 2302
# )


# 修改，跟增加的用法一样

dic1["hobbies"] = ["唱歌", "跳舞", "打篮球", "rap"]
print(dic1)


# 删除

# del dic1["study_year"]
# print(dic1)

study_year = dic1.pop("study_year")
print("study_year: ", study_year)
print(dic1)


# 获取字典长度

print(
    len(dic1)       # 获取键值对数量
)


print()
print()
# 遍历
# 遍历所有的键 dic.keys()
for k in dic1.keys():
    print(k)

print()
print()
# 遍历所有的值，dic.values()
for v in dic1.values():
    print(v)


print()
print()
# 遍历所有的键值对 dic.items()
for k, v in dic1.items():
    print(f"key: {k}；value: {v}")


print()
print()
# 字典推导式
dic3 = {}
for i in range(10):
    if i % 2 == 0:
        dic3[i] = i**2

print(dic3)

dic4 = {i: i**2 for i in range(10) if i % 2 == 0}
print(dic4)


# 字典的成员判断

print(
    "张三" in dic1
)

